const Koa = require('koa');
const XLSX = require('xlsx');
const cors = require('koa2-cors');

const app = new Koa();


const titles = ['姓名', '年龄', '性别'];
const data = [
  { name: '陈小瓦', age: 18, sex: '男' },
  { name: '李飞', age: 33, sex: '男' },
  { name: '林妹妹', age: 22, sex: '女' },
  { name: '小明', age: 10, sex: '男' },
  { name: '小红', age: 9, sex: '男' },
  { name: '小军', age: 11, sex: '男' },
  { name: '小丽', age: 18, sex: '女' },
  { name: '甲', age: 45, sex: '男' },
  { name: '乙', age: 21, sex: '男' },
  { name: '丁', age: 55, sex: '女' },
  { name: '武丑', age: 100, sex: '男' },
  { name: '子牛', age: 101, sex: '男' },
  { name: '盐虎', age: 102, sex: '男' },
  { name: '峰儿', age: 26, sex: '男' },
  { name: '坤鸡', age: 22, sex: '男' },
];

app.use(cors());

app.use((ctx, next) => {
  if (ctx.path === '/') {
    next();
    return;
  }
  //不是根目录访问全部返回404
  ctx.status = 404;
});

app.use((ctx, next) => {
  const name = ctx.query["name"];
  //获取查询条件查询
  const queryData = data.filter(p => p.name.includes(name));

  let result, mimeType, filename;

  if (queryData.length > 0) {

    const xlsData = [titles];
    for (const item of queryData) {
      let d = [item.name, item.age, item.sex];
      xlsData.push(d);
    }
    //json转excel
    let sheet = XLSX.utils.aoa_to_sheet(xlsData);
    //excel转node文件流
    result = sheetToBuffer(sheet);
    mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    filename = `attachment;filename=${encodeURIComponent('人员列表')}.xlsx`;
  } else {
    result = { msg: '无数据可导出' };
    mimeType = "application/json; charset=utf-8";
  }

  ctx.body = result;
  ctx.set("Content-Type", mimeType);
  if (filename) {
    ctx.set("Content-Disposition", filename);
  }
  ctx.status = 200;
});

app.listen(3001);















/**
 * 获取excel文件流
 * @param {*} sheet 
 * @param {*} sheetName 
 */
function sheetToBuffer(sheet, sheetName) {
  sheetName = sheetName || 'sheet1';
  let workbook = {
    SheetNames: [sheetName],
    Sheets: {}
  };
  workbook.Sheets[sheetName] = sheet;
  // 生成excel的配置项
  let wopts = {
    bookType: 'xlsx', // 要生成的文件类型
    type: 'buffer'
  };
  let wbout = XLSX.write(workbook, wopts);
  return wbout;
}